package m.jclecai.com.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.activity.LoginActivity;
import m.jclecai.com.bean.RegisterBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.callback.ClickCallBack;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.dialog.DialogUtils;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.utils.MD5;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.SystemUtils;

/**
 * 在原来的基础上增加有公共标题栏的基类
 */
public abstract class BaseActivity extends ISuperBaseActivity {

    @Nullable
    @BindView(R.id.tv_back)
    protected TextView tvBack;

    @Nullable
    @BindView(R.id.tv_mid_title)
    protected TextView tvMidTitle;

    @Nullable
    @BindView(R.id.tv_right_option)
    protected TextView tvRightOption;
    //标题栏容器
    @Nullable
    @BindView(R.id.rl_bar)
    protected RelativeLayout rlBar;
    //正文内容容器
    protected FrameLayout vBody;
    //界面容器
    @Nullable
    @BindView(R.id.activity_base)
    protected RelativeLayout activityBase;
    @Nullable
    @BindView(R.id.iv_title_icon)
    protected ImageView ivTitleIcon;
    @Nullable
    @BindView(R.id.v_title_fill)
    protected View v_title_fill;

    private FragmentManager fm;
    private BaseFragment mCurrentFragment;

    protected String TAG = this.getClass().getName();

    public static ClickCallBack callBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerRandom();
        mWaitingDialog = new DialogUtils(this);
        fm = getSupportFragmentManager();
        setContentView(R.layout.activity_base);
        vBody = (FrameLayout) findViewById(R.id.v_body);
        View.inflate(this, getContentView(), vBody);
        initLoadingView();
        ButterKnife.bind(this);
        tvBack.setVisibility(View.INVISIBLE);
        tvMidTitle.setVisibility(View.INVISIBLE);
        tvRightOption.setVisibility(View.INVISIBLE);
        ivTitleIcon.setVisibility(View.GONE);
        initView();
        initData();
        initListener();
        int color = getStatusBarColor();
        if (tvBack.getVisibility() == View.INVISIBLE
                && tvMidTitle.getVisibility() == View.INVISIBLE
                && tvRightOption.getVisibility() == View.INVISIBLE) {
            rlBar.setBackgroundColor(ContextCompat.getColor(this, R.color.b));
            rlBar.setVisibility(View.GONE);
            v_title_fill.setVisibility(View.GONE);
            if (color == -1)
                color = R.color.b;
            if (!hideCoustomStatusBar())
                StatusBarUtil.setColorNoTranslucent(this, ContextCompat.getColor(this, color));
        } else {
            if (color == -1)
                color = R.color.color_home;
            if (!hideCoustomStatusBar())
                StatusBarUtil.setColorNoTranslucent(this, ContextCompat.getColor(this, color));
        }
        resetWindow();
    }


    /**
     *  设置回调
     * @param Back
     */
    public static void setClickCallBack(ClickCallBack Back){
        callBack = Back;
    }
    /**
     * 这里是重置Activity的background，
     * 如果没有重写的话，默认是没有背景，
     * 如果我们需要背景的话，我们重写这个方法就可以了
     */
    protected void resetWindow(){
       // getWindow().setBackgroundDrawable(null);
    }

    //这里面我们要做的一个操作就是加载view;
    protected  void initLoadingView(){

    }

    //是否允许body覆盖title
    protected void allowBodyCoverTitle(boolean bool) {
        v_title_fill.setVisibility(bool ? View.GONE : View.VISIBLE);
        if (tvBack.getVisibility() == View.INVISIBLE
                && tvMidTitle.getVisibility() == View.INVISIBLE
                && tvRightOption.getVisibility() == View.INVISIBLE) {
            v_title_fill.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected boolean hideCoustomStatusBar() {
        return false;
    }

    public BaseFragment getCurrentFragment() {
        return mCurrentFragment;
    }

    public void repalce(BaseFragment fragment) {
        FragmentTransaction ft = fm.beginTransaction();
//        ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
        if (!fragment.isAdded())
            if (mCurrentFragment == null)
                ft.add(R.id.viewBody, fragment).show(fragment);
            else
                ft.add(R.id.viewBody, fragment).hide(mCurrentFragment).show(fragment);
        else
            ft.hide(mCurrentFragment).show(fragment);
        mCurrentFragment = fragment;
        ft.commitAllowingStateLoss();
    }

    protected void setTitle(String text) {
        setTitle(text, -1);
    }

    //右边按钮的文本 drawable -1 代表不加图案
    @Override
    protected void setTitle(String txt, int drawable) {
        tvMidTitle.setVisibility(View.VISIBLE);
        tvMidTitle.setText(txt);
        if (drawable > -1) {
            ivTitleIcon.setVisibility(View.VISIBLE);
            ivTitleIcon.setImageResource(drawable);
        }
    }

    //左边按钮 = 返回
    protected void leftOptionText(String text) {
        leftOptionText(text, -1);
    }

    @Override
    protected void leftOptionText(String text, int drawable) {
        tvBack.setVisibility(View.VISIBLE);
        tvBack.setText(text);
        if (drawable > -1)
            tvBack.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, drawable), null, null, null);
    }

    @OnClick(R.id.tv_back)
    protected void close() {
        finish();
    }

    @OnClick(R.id.tv_right_option)
    protected void rightClick() {
        if (callBack != null){
            callBack.OnClick();
        }
    }

    protected void rightOptionText(String text) {
        rightOptionText(text, -1);
    }

    @Override
    protected void rightOptionText(String text, int drawable) {
        tvRightOption.setVisibility(View.VISIBLE);
        tvRightOption.setText(text);
        if (drawable > -1)
            tvRightOption.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, drawable), null, null, null);
    }

    protected void startAnimation(View view, int animation) {
        Animation operatingAnim = AnimationUtils.loadAnimation(this, animation);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        view.startAnimation(operatingAnim);
    }

    protected boolean isLogin() {
        return PreferenceUtil.isLogin(this);
    }

    @Override
    protected int getStatusBarColor() {
        return R.color.color_home;
    }

    protected void checkLogin(Callback callback) {
        this.callback = callback;
        if (!isLogin()) {
            startActivityForResult(new Intent(this, LoginActivity.class), Constant_Result.NEEDLOGIN);
        } else {
            callback.callbackSuccess();
        }
    }

    //默认需要md5加密
    protected void logIn(String user, String password, final Callback callback) {
        logIn(user, password, true, callback);
    }

    //自动登录
    protected void logIn(String user, String password, boolean isMd5, final Callback callback) {
        this.callback = callback;
        //收起软键盘
        showDialog();
        //登录
        final String userPass = isMd5 ? MD5.getMD5(password) : password;
        final Map<String, String> pair = new HashMap<String, String>();
        pair.put("user", user);
        pair.put("password", userPass);
        pair.put("version", SystemUtils.getCurrentVersionCode(BaseActivity.this));
        pair.put("channel", "android_"+ Build.VERSION.RELEASE+"_"+Build.MODEL);
        HttpManager.postAsyn(Constant_Url.LOGIN_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                if (callback != null)
                    callback.callbackField();
                //失败
                MyToast.showToast(BaseActivity.this, "无法连接服务器");
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                //登陆成功
                RegisterBean registerBean = FastOk.get(response, RegisterBean.class);
                if (registerBean == null) {
                    if (callback != null)
                        callback.callbackField();
                    return;
                }
                MyToast.showToast(BaseActivity.this, registerBean.getMessage());
                if ("0".equals(registerBean.getStatus())) {
                    loadUserInfo(pair);
                } else {
                    if (callback != null)
                        callback.callbackField();
                }
            }
        }, pair);
    }

    //登录后需要加载用户信息
    private void loadUserInfo(final Map<String, String> pair) {
        showDialog();
        HttpManager.postAsyn(Constant_Url.GET_USER_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                if (callback != null)
                    callback.callbackField();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                UserBean userBean = FastOk.get(response, UserBean.class);
                if (userBean != null) {
                    if ("1011".equals(userBean.getStatus())) {
                        MyToast.showToast(BaseActivity.this, "获取用户信息失败！");
                        PreferenceUtil.writeUser(BaseActivity.this, null);
                        if (callback != null)
                            callback.callbackField();
                    } else {
                        PreferenceUtil.setAccount(BaseActivity.this, userBean.getPhone());
                        PreferenceUtil.setUserName(BaseActivity.this, userBean.getUsername());
                        PreferenceUtil.setPassword(BaseActivity.this, pair.get("password"));
                        PreferenceUtil.setLoginStatus(BaseActivity.this, true);
                        PreferenceUtil.writeUser(BaseActivity.this, userBean);
                        if (callback != null)
                            callback.callbackSuccess();
                    }
                } else {
                    MyToast.showToast(BaseActivity.this, getString(R.string.error_network));
                    if (callback != null)
                        callback.callbackField();
                }
            }
        }, pair);
    }

    /**
     * 按钮操作枚举 彩种 属相 赌注 时间(生日)
     */
    protected enum ACTION {
        CAIZHONG, SHUXIANG, DUZHU, SHIJIAN
    }

    @Override
    protected void onDestroy() {
        unRegisterRandom();
        super.onDestroy();
    }

    //注册机选广播
    void registerRandom() {
        String packageName = getClass().getName();
        if (packageName.contains("ui"))
            if (packageName.contains("BetConfirmActivity"))
                registerReceiver(receiver, new IntentFilter(Constant_Result.EXECRANDOMLOTTERYNUM));
            else
                registerReceiver(receiver, new IntentFilter(Constant_Result.RANDOMLOTTERYNUM));
    }

    void unRegisterRandom() {
        String packageName = getClass().getName();
        if (packageName.contains("ui"))
            unregisterReceiver(receiver);
        receiver = null;
    }

    //机选广播(给特定的需要机选的界面用)
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(Constant_Result.RANDOMLOTTERYNUM.equals(intent.getAction())){
                sendRandom(intent);
            }else if(Constant_Result.EXECRANDOMLOTTERYNUM.equals(intent.getAction())){
                execRandom(intent);
            }
        }
    };

    protected void sendRandom(Intent intent) {

    }

    protected void execRandom(Intent intent) {

    }
}
